package com.ms.service.module.redpoint.db;

import java.lang.reflect.Method;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xpec.c4.game.cronjob.CronTaskTimer;
import com.xpec.c4.game.utility.GameUtility;
import com.xpec.c4.service.module.task.TaskAsyncCommand;

public class TimerExecuteAsync extends TaskAsyncCommand{
	/**
	 * 是否需要更新行程到redis
	 */
	public boolean needUpdateSchedule;
	
	/**
	 * 是哪個timer 要做這件事情 
	 * 因為結束後如果needUpdateSchedule = true 
	 * 要更新行程到redis
	 */
	public CronTaskTimer cronTaskTimer;
	
	/** log4j object */
	private static final Log log = LogFactory.getLog(TimerExecuteAsync.class);

	/** 觸發後呼叫的方法所在的 class */
	private Object classOfMethod;

	/** 觸發後呼叫的方法 */
	private Method method;
	
	private Object[] params;
	
	
	/**
	 * 如果不帶參數 </br>
	 * paramClz 帶 new Class[]{}</br>
	 * paramValue 帶 new Object[]{}</br>
	 * 如果要帶參數 ex: </br>
	 * Class[] clz = new Class[]{Long.class}; </br>
	 * Object[] params = new Object[]{TimeSys.currentTimeMills()}; </br>
	 * 如果方法參數是大寫Long那Class[]就要放大寫Long.class 反之</br>
	 * 不然會打不開</br>
	 * @param classOfMethod
	 * @param methodName
	 * @param paramClz
	 * @param paramValue
	 */
	public TimerExecuteAsync(Class<?> classOfMethod, String methodName, Class[] paramClz ,Object[] paramValue) {
		super();
		if (classOfMethod == null) {
			return;
		}

		params = paramValue;

		this.classOfMethod = classOfMethod;

		if (GameUtility.isHaveString(methodName)) {
			try {
				method = classOfMethod.getMethod(methodName, paramClz);
			} catch (Exception e) {
				if (log.isErrorEnabled()) {
					log.error("TimerExecuteAsync()", e);
				}
			}
		} else {
			method = null;
		}
	}

	
	
	@Override
	public void asyncExecute() throws Exception {
		if (classOfMethod == null) {
			return;
		}

		if (method == null) {
			return;
		}

		try {
			
			method.invoke(classOfMethod, params);
			
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("TimerExecutionAsync.asyncExecute()", e);
			}
		}
		
		if(needUpdateSchedule){
			if(cronTaskTimer == null)
				return;
			moduleServer.addCronTaskTimerNewSchedule(cronTaskTimer);
		}
	}

	@Override
	public void execute() throws Exception {
		
	}

}
